<!-- -->
<template>
  <div class="shop">
    <el-container>
      <el-header>
        <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            title="批量删除"
            @click="deleteAll()"
          >批量删除</el-button>
        <el-input v-model="searchShop" placeholder="请输入店铺名称"></el-input>
        <el-button type="primary" @click="searchShopList()">搜索店铺</el-button>
        <el-button type="success" @click="dialogVisible = true"
          >添加店铺</el-button
        >
        <el-button type="success" @click="refresh()">刷新</el-button>
        <el-dialog title="添加店铺" :visible.sync="dialogVisible" width="30%">
          <el-form
            :label-position="labelPosition"
            label-width="80px"
            :model="addForm"
          >
            <el-form-item label="店铺昵称">
              <el-row>
                <el-col :span="20">
                  <el-input v-model="addForm.nickname"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="店主名称">
              <el-row>
                <el-col :span="20">
                  <el-input v-model="addForm.username"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="店铺类型">
              <el-row>
                <el-col :span="20">
                  <el-select v-model="addForm.cid">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="店铺地址">
              <el-row>
                <el-col :span="20">
                  <el-cascader
                    v-model="addForm.address"
                    :options="provinceList"
                  ></el-cascader>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addShop()">确 定</el-button>
          </span>
        </el-dialog>
      </el-header>
      <el-main>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <span class="total">共有数据 {{totalSize}} 条</span>
        <el-table :data="tableData" style="width: 100%;margin-top:2%;">
          <el-table-column
              align ="center"
              width = "60">
              <template slot-scope="scope">
                <el-checkbox-group v-model="checkedId" @change="handleCheckedChange">
                  <el-checkbox :key="scope.row.id" :label="scope.row.id">{{""}}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
          <el-table-column label="店铺ID" prop="id"></el-table-column>
          <el-table-column label="店铺名称" prop="name"></el-table-column>
          <el-table-column label="关联用户" prop="username"></el-table-column>
          <el-table-column
            label="创建时间"
            prop="_createTime"
          ></el-table-column>
          <el-table-column
            label="更新时间"
            prop="_updateTime"
          ></el-table-column>
          <el-table-column label="状态" prop="_status"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="
                  handleEdit(scope.$index, scope.row), (dialogVisible1 = true)
                "
                >修改</el-button
              >
              <el-dialog
                title="修改店铺"
                :visible.sync="dialogVisible1"
                width="60%"
              >
                <el-form
                  :label-position="labelPosition"
                  label-width="80px"
                  :model="fixForm"
                >
                  <el-form-item label="名称">
                    <el-row>
                      <el-col :span="6">
                        <el-input
                          v-model="fixForm.name"
                          placeholder="请输入该商品的名称"
                          auto-complete="on"
                        ></el-input>
                      </el-col>
                      <el-col
                        :span="2"
                        style="text-align:right;padding-right:14px;"
                        >店主</el-col
                      >
                      <el-col :span="6">
                        <el-input
                          v-model="fixForm.username"
                          placeholder="请输入店主名字"
                          auto-complete="on"
                        ></el-input>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="店铺类型">
                    <el-row>
                      <el-col :span="20">
                        <el-select v-model="fixForm.cid" auto-complete="on">
                          <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          >
                          </el-option>
                        </el-select>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="地址">
                    <el-row>
                      <el-col>
                        <el-cascader
                          v-model="fixForm.address"
                          :options="provinceList"
                          auto-complete="on"
                        ></el-cascader>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible1 = false">取 消</el-button>
                  <el-button
                    type="primary"
                    @click="(dialogVisible1 = false), fixShop()"
                    >确 定</el-button
                  >
                </span>
              </el-dialog>
              <el-button
                size="mini"
                type="danger"
                @click.native.prevent="handleDelete(scope.$index, scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer>
        <el-button @click="pre" :disabled="preBool">上一页</el-button>
        <el-input
          v-model="pageNum"
          readonly="readonly"
          style="width:60px;"
        ></el-input>
        <el-button @click="add" :disabled="addBool">下一页</el-button>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import province from "./AddressList.js";
export default {
  name: "Shop",
  data() {
    return {
      dialogVisible: false,
      dialogVisible1: false,
      searchShop: "",
      addForm: {
        id: "",
        nickname: "",
        address: "",
        cid: "",
        username: ""
      },
      options: [],
      provinceList: [],
      labelPosition: "right",
      tableData: [],
      fixForm: {
        id: "",
        cid: "",
        status: "",
        category: "",
        name: "",
        address: [],
        province: "",
        city: "",
        street: "",
        uid: "",
        username: "",
        createTime: "",
        updateTime: ""
      },
      // 分页
      pageNum: 1,
      addBool: false,
      preBool: true,
      pageSize: 10,
      totalPages: "",
      totalSize: "",
      pages: "",

       // 全选
      checkAll: false,
      checkedId: [],
      isIndeterminate: true,
    };
  },
  watch: {
    pageNum: function(Val) {
      if (Val === 1) {
        this.preBool = true;
        this.addBool = false;
      } else if (Val === this.totalPages) {
        this.addBool = true;
        this.preBool = false;
      } else {
        this.preBool = false;
        this.addBool = false;
      }
    }
  },
  created() {
    this.getShopList();
    this.getShopCategory();
    // console.log(province);
    this.provinceList = province;
    // console.log(this.provinceList);
    // this.changeProvince();
  },

  components: {},

  filters: {},

  computed: {},

  methods: {
    handleCheckedChange(value = []) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tableData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableData.length;
      console.log(this.checkedId)
    },
    handleCheckAllChange(val) {
      this.checkedId = []
      this.checkAll = val;
      this.isIndeterminate = !val;
      if(this.checkAll) {
        this.tableData.forEach(data => {
          this.checkedId.push(data.id);
        });
      }
      console.log(this.checkedId)
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.fixForm = row;
      this.fixForm.address = [];
      this.fixForm.address[0] = row.province;
      this.fixForm.address[1] = row.city;
      this.fixForm.address[2] = row.street;
    },

    handleDelete(index, id) {
      console.log(index, id);
      this.$confirm("此操作将永久删除该店铺信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteShop(index, id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    add() {
      if (this.pageNum < this.totalPages) {
        this.pageNum++;
        this.getShopList();
      } else {
        this.addBool = true;
      }
    },
    pre() {
      if (this.pageNum > 1) {
        this.pageNum--;
        this.getShopList();
      } else {
        this.preBool = true;
      }
    },
    // 成功函数
    Success(index) {
      this.$message.success(index);
    },
    // 失败函数
    Fail(index) {
      this.$message.error(index);
    },
    // 刷新
    refresh() {
      this.pageNum = 1;
      this.pageSize = 10;
      this.searchShop = "";
      // console.log(this.pageNum);
      // console.log(this.pageSize);
      this.getShopList();
    },
    changeProvince() {
      for (let i in province) {
        this.provinceList[i] = {
          value: province[i].name,
          label: province[i].name,
          children: []
        };
        for (let k in province[i].city) {
          this.provinceList[i].children[k] = {
            value: province[i].city[k].name,
            label: province[i].city[k].name,
            children: []
          };
          for (let j in province[i].city[k].districtAndCounty) {
            this.provinceList[i].children[k].children[j] = {
              value: province[i].city[k].districtAndCounty[j],
              label: province[i].city[k].districtAndCounty[j]
            };
          }
        }
      }
      // console.log(JSON.stringify(this.provinceList));
    },
    getShopList() {
      this.axios
        .put("/api/merchants", {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            let list = res.data.data;
            this.totalPages = list.totalPages;
            this.totalSize = list.totalSize;
            this.pageNum = list.pageNum;
            this.pageSize = list.pageSize;
            for (let item of list.content) {
              item._updateTime = item.updateTime ? item.updateTime : "暂无更新";
              item._status = item.status ? "启用" : "禁用";
              item._createTime = item.createTime ? item.createTime : "暂无记录";
            }
            this.tableData = list.content;
          }else{
            this.totalPages = 0;
            this.totalSize = 0;
            this.tableData = [];
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getShopCategory() {
      this.axios
        .get("/api/merchantsCategory")
        .then(res => {
          // console.log(res.data);
          if (res.data.code === 200) {
            let bufferList = [];
            for (let key in res.data.data.list) {
              let i = new Object();
              i.value = res.data.data.list[key].id;
              i.label = res.data.data.list[key].name;
              bufferList.push(i);
            }
            this.options = bufferList;
            // console.log(this.options);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 搜索店铺
    searchShopList() {
      this.pageNum = 1;
      this.pageSize = 10;
      this.axios
        .put("/api/merchants", {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.searchShop
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            this.Success("查询成功");
            this.tableData = [];
            let list = res.data.data;
            this.totalPages = list.totalPages;
            this.totalSize = list.totalSize;
            this.pageNum = list.pageNum;
            this.pageSize = list.pageSize;
            for (let item of list.content) {
              item._updateTime = item.updateTime ? item.updateTime : "暂无更新";
              item._status = item.status ? "启用" : "禁用";
              item._createTime = item.createTime ? item.createTime : "暂无记录";
            }
            this.tableData = list.content;
          } else {
            this.Fail("查找失败");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    addShop() {
      
      this.axios
        .post("/api/user/findByName", {
          username: this.addForm.username
        })
        .then(res => {
          // console.log(res.data);
          if (res.data.code === 200) {
            this.addForm.id = res.data.data.id;

            if (
              this.addForm.cid === "" ||
              this.addForm.nickname === "" ||
              this.addForm.username === "" ||
              this.addForm.address === ""
            ) {
              this.Fail("信息不足，请填写足够信息");
            } else {
              this.dialogVisible = false;
              this.axios
                .post("/api/merchants", {
                  name: this.addForm.nickname,
                  uid: this.addForm.id,
                  cid: this.addForm.cid,
                  province: this.addForm.address[0],
                  city: this.addForm.address[1],
                  street: this.addForm.address[2]
                })
                .then(res => {
                  console.log(res.data);
                  if (res.data.code === 200) {
                    this.Success("添加成功");
                    this.getShopList();
                  }
                })
                .catch(error => {
                  console.log(error);
                });
            }
          } else {
            this.Fail("该用户不存在，请填写正确用户名");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // checkUsername() {
    //   this.axios
    //     .post("/api/user/findByName", {
    //       username: this.fixForm.username
    //     })
    //     .then(res => {
    //       // console.log(res.data);
    //       if (res.data.code === 200) {
    //         this.fixForm.uid = res.data.data.id;
    //       } else {
    //         this.Fail("该用户不存在，请填写正确用户名");
    //       }
    //     })
    //     .catch(error => {
    //       console.log(error);
    //     });
    // },
    fixShop() {
      console.log(this.fixForm.address);
      this.axios
        .post("/api/user/findByName", {
          username: this.fixForm.username
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            this.fixForm.uid = res.data.data.id;

            if (
              this.fixForm.uid === "" ||
              this.fixForm.name === "" ||
              this.fixForm.username === "" ||
              this.fixForm.address === ""
            ) {
              this.Fail("信息不足，请填写足够信息");
            } else {
              this.dialogVisible1 = false;
              console.log({
                  id: this.fixForm.id,
                  name: this.fixForm.nickname,
                  uid: this.fixForm.uid,
                  cid: this.fixForm.cid,
                  province: this.fixForm.address[0],
                  city: this.fixForm.address[1],
                  street: this.fixForm.address[2]
                })
              this.axios
                .post("/api/merchants", {
                  id: this.fixForm.id,
                  name: this.fixForm.name,
                  uid: this.fixForm.uid,
                  cid: this.fixForm.cid,
                  province: this.fixForm.address[0],
                  city: this.fixForm.address[1],
                  street: this.fixForm.address[2]
                })
                .then(res => {
                  console.log(res.data);
                  if (res.data.code === 200) {
                    this.Success("修改成功");
                    this.getShopList();
                  }
                })
                .catch(error => {
                  console.log(error);
                });
            }
          } else {
            this.Fail("该用户不存在，请填写正确用户名");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    deleteShop(index, id) {
      this.axios
        .delete("/api/merchants", {
          params: {
            ids: id
          }
        })
        .then(res => {
          console.log(res);
          if (res.data.code === 200) {
            this.Success("删除成功");
            this.tableData.splice(index, 1);
            this.getShopList();
          } else {
            this.Fail("删除失败");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    deleteAll() {
      var data = {
        ids: this.checkedId
      }
      var params = this.qs.stringify(data, { indices: false })
      this.axios.delete('/api/merchants?'+params
      ).then(response => {
        console.log(response);
        if(response.data.code == 200) {
          this.getShopList();
          this.Success("删除成功");
        } else {
          this.Fail("删除失败");
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
};
</script>
<style scoped>
.total {
  font-size: 14px;
  margin-left: 50px;
  color: #606266;
}
.shop {
  width: 100%;
  height: 100%;
}
.el-container {
  height: 100%;
  width: 100%;
}
.el-header {
  line-height: 60px;
}
.el-header .el-input {
  width: 240px;
  margin-right: 14px;
}
.el-main {
  width: 100%;
  height: 100%;
}
.el-footer {
  line-height: 60px;
  text-align: right;
}
.el-form-item .el-input,
.el-form-item .el-cascader,
.el-form-item .el-select {
  width: 100%;
}
</style>